//
//  Encrypt.m
//  EFExtend
//
//  Created by mac on 15/7/4.
//  Copyright (c) 2015年 Eric. All rights reserved.
//

#import "Encrypt.h"


@interface Encrypt ()

@end

@implementation Encrypt
#define kENCRYPTKey @"d985ca5f92e3ed87a71753bbc4fbf5c9"
#define kENCRYPTIv  @"AFDFSDFSDFDSDSFE"

- (void)dealloc
{
   
    HM_SUPER_DEALLOC();
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    [self.customNavLeftBtn setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [self.customNavLeftBtn setFrame:CGRectMakeBound(32, 32)];
     //  1. Encryption:
    NSDictionary *dic = @{@"test":@"test",@"pwd":@"tttt"};
     NSString * secret = [dic JSONString]; // this is the text that you want to encrypt.
    secret  = @"data";
     NSString * key = @"shared secret"; //secret key for encryption. To make encryption stronger, we will not use this key directly. We'll first hash the key next step and then use it.
    
     key = [[StringEncryption alloc] sha256:key length:32]; //this is very important, 32 bytes = 256 bit
    
    NSString * iv =  @"AFDFSDFSDFDSDSFE";//[[[[StringEncryption alloc] generateRandomIV:11]  base64EncodingWithLineLength:0] substringToIndex:16]; //Here we are generating random initialization vector (iv). Length of this vector = 16 bytes = 128 bits
    
//     Now that we have input text, hashed key and random IV, we are all set for encryption:
     NSData * encryptedData = [[StringEncryption alloc] encrypt:[secret dataUsingEncoding:NSUTF8StringEncoding] key:key iv:iv];
    
     NSLog(@"encrypted data string:%@ key:%@ iv:%@:%@ >print: %@",secret ,key,iv,[encryptedData description],[encryptedData  base64EncodingWithLineLength:0]); //print the encrypted text
//     Encryption = [plainText + secretKey + randomIV] = Cyphertext
    
     // 2. Decryption
//     for decryption, you will have to use the same IV and key which was used for encryption.
    
     encryptedData = [[StringEncryption alloc] decrypt:encryptedData  key:key iv:iv];
     NSString * decryptedText = [[NSString alloc] initWithData:encryptedData encoding:NSUTF8StringEncoding];
     NSLog(@"decrypted data:: %@", decryptedText); //print the decrypted text
    
    __weak_type __typeof(NSData*)encryptedDataSS = encryptedData;
    
//    [[[[[self webApiUniqueCommand:@"http://www.baidu.com/cc" timeout:20.f] setWebMethod:@"UPLOAD"] setWebUploadBlock:^(id<AFMultipartFormData> formData) {
////        [formData appendPartWithFormData:encryptedDataSS name:@"data"];
//        [formData appendPartWithFileURL:[[NSBundle mainBundle] URLForResource:@"FontAwesome" withExtension:@"ttf"] name:@"data" error:nil];
//        INFO(        self.view);
////        int a = 0;
//    }] setWebListenProcess] send];

//    [[[[self webApiUniqueCommand:@"http://www.baidu.com/comm" timeout:20.f] setWebMethod:@"POST"]  setWebParams:dic] send];
    
    [self send:@{@"data":@"data"} to:@"http://202.100.180.20/api.do?getVerity" encrypt:YES alias:@"getVerity"];
    
}

- (HMDialogue *)upload:(NSData*)data to:(NSString*)command alias:(NSString*)alias{
    HMDialogue *dia = [[[[[[self webApiWithCommand:command timeout:20.f] setWebName:alias] setWebMethod:@"POST"] setWebHttpMock:[HMWebAPI methodMockSuccess]] setWebUrlEncoding:NSUTF8StringEncoding] setWebData:data];
    
    
//        HMDialogue *dia = [[[[[self webApiWithCommand:command timeout:20.f] setWebName:alias] setWebMethod:@"UPLOAD"] setWebHttpMock:[HMWebAPI methodMockSuccess]] setWebUploadBlock:^(id<AFMultipartFormData> formData) {
//            NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
//            [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\";", @"data"] forKey:@"Content-Disposition"];
//            [mutableHeaders setValue:@"multipart/form-data;charset=UTF-8" forKey:@"Content-Type"];
//            [formData appendPartWithHeaders:mutableHeaders body:data];
////            [formData appendPartWithFormData:data name:@"data"];
////            [formData appendPartWithFileData:data name:@"data" fileName:@"" mimeType:@"multipart/form-data;"];
//        }];
    [dia send];
    return  dia;
}

- (HMDialogue *)get:(NSDictionary*)dic to:(NSString*)command alias:(NSString*)alias{
    HMDialogue *dia = [[[[self webApiWithCommand:command timeout:20.f] setWebName:alias] setWebParams:dic] setWebMethod:@"POST"];
    [dia send];
    return  dia;
}

- (void)send:(NSDictionary*)dic to:(NSString*)command encrypt:(BOOL)encrypt alias:(NSString*)alias{
    dic = @"{\"phone\":\"13489184949\"}";
    
//    [self get:@{@"data":@"data"} to:command alias:alias];
//    return;
    NSData * encryptedData = [[dic isKindOfClass:[NSString class]]?(NSString*)dic:[dic JSONString] dataUsingEncoding:NSUTF8StringEncoding];
    
    INFO([[encryptedData description] trim]);
    if (encrypt) {
        encryptedData = [[StringEncryption alloc] encrypt:encryptedData key:kENCRYPTKey iv:kENCRYPTIv];
    }
    INFO([[encryptedData description] trim],[encryptedData base64EncodingWithLineLength:0]);
    
//    [[self upload:encryptedData to:command alias:alias] setWebUserinfo:dic];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

ON_Button(signal){
    UIButten *btn = signal.source;
    if ([signal is:[UIButten TOUCH_UP_INSIDE]]) {
        if ([btn is:@"leftBtn"]) {//customNavLeftBtn
            [self backAndRemoveWithAnimate:YES];
        }else if ([btn is:@"rightBtn"]){//customNavRightBtn
            
        }
    }
}

ON_WebAPI(dlg){
    if (dlg.sending) {
        
        
    }else if (dlg.progressed){
        // 必须在发送web Api 时指定 setWebProcess:YES
        //          dlg.ownRequest.downloadPercent;
        //          dlg.ownRequest.uploadPercent;
        CC(@"UPLoad",@(dlg.ownRequest.uploadPercent));
    }else if (dlg.succeed){
        NSDictionary *dic = [dlg.output objectForKey:[HMWebAPI params]];
        
        
    }else if (dlg.failed){
        if (dlg.timeout) {
            [self showFailureTip:@"操作失败" detail:@"链接超时" timeOut:2.f];
            return;
        }
        
        [self showFailureTip:@"网络链接失败" detail:@"数据不存在或网络错误" timeOut:3.f];
    }else if (dlg.cancelled){
        [self showFailureTip:@"操作失败" detail:@"链接已取消" timeOut:2.f];
    }
}

@end
